package com.yksj.healthtalk.ui.salon;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.cropimage.CropUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.universalimageloader.utils.StorageUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.yksj.healthtalk.adapter.salonInfoTypeAdapter;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.CommonExplainActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.entity.GroupInfoEntity;
import com.yksj.healthtalk.entity.TagEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.chatting.ChatActivity;
import com.yksj.healthtalk.ui.interestwall.TagChooseActivity;
import com.yksj.healthtalk.ui.salon.SalonSelectPaymentOptionActivity.OnBuyTicketHandlerListener;
import com.yksj.healthtalk.utils.BitmapUtils;
import com.yksj.healthtalk.utils.ImageUtils;
import com.yksj.healthtalk.utils.SalonHttpUtil;
import com.yksj.healthtalk.utils.SystemUtils;
import com.yksj.healthtalk.utils.ToastUtil;
import com.yksj.healthtalk.utils.WheelUtils;

/**
 * @ClassName: SalonNewActivity
 * @Description:创建新话题
 * @author
 * @date 2013-1-6 上午9:52:15
 */
public class SalonNewActivity extends BaseFragmentActivity implements
		OnClickListener, OnItemClickListener,OnBuyTicketHandlerListener {
	private TextView mTitle;
	private Button mCreatSalonBtn;
	private EditText mSalonName;// 话题名称
	private Button mSalonDescribe;// 话题描述
	private ToggleButton isDoctorToggleBtn;// 是否是医师话题
	private ToggleButton isAcceptMessageToggleBtn;// 是否接受消息推送
	private ToggleButton isOpenToggleButton;// 是否在消息厅发布
	private Button mTitleBackBtn;// 返回按钮
	private final int WHAT_FAILE = -1;
	private final int WHAT_SUCC = 1;
	private PopupWindow mPopupWindow;
	private ImageView mInfoHeadIv;
	private File storageFile;
	private String path;
	private GridView mGridView;
	private salonInfoTypeAdapter adapter;// 标签适配器
	private List<String> strs;// 标签数据
	private StringBuilder tagId;
	private StringBuilder tagName;
	private StringBuilder upperId;
	private ArrayList<TagEntity> tags;// 标签返回类型
	private ArrayList<TagEntity> bufferTags;
	private Set<String> deleteRepeatSet;// 大类去重
	private RelativeLayout isDoctorSalonLinearLayout;
	private RelativeLayout isAcceptMessageLinearLayout;
	public static final int CAMERA_REQUESTCODE = 3;
	private static final int PHOTO_PICKED_WITH_DATA = 1;
	private static final int TAG_CHOOSE_REQUESTCODE = 2;
	private LodingFragmentDialog dialog;
	private boolean isDoctorSalon = false;
	private GroupInfoEntity entity;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case WHAT_FAILE:
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				if (msg.obj != null) {
					SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),String.valueOf(msg.obj));
				} else {
					ToastUtil.showShort(SalonNewActivity.this,R.string.groupNewFail);
				}
//				GroupInfoEntity entity = SalonHttpUtil.jsonAnalysisSalonEntity(SalonNewActivity.this,(String) msg.obj).get(0);
//				SalonHttpUtil.onItemClick(SalonNewActivity.this, SalonNewActivity.this, getSupportFragmentManager(),entity, true);
				break;
			case WHAT_SUCC:
				LodingFragmentDialog.dismiss(getSupportFragmentManager());
				GroupInfoEntity entity = SalonHttpUtil.jsonAnalysisSalonEntity(SalonNewActivity.this,(String) msg.obj).get(0);
				SalonHttpUtil.onItemClick(SalonNewActivity.this, SalonNewActivity.this, getSupportFragmentManager(),entity, true);
				SalonNewActivity.this.finish();
				//				ToastUtil.showShort(SalonNewActivity.this,R.string.groupNewSucc);
//				if (SmartFoxClient.getLoginUserId() != null) {
//					SalonHttpUtil.jsonAnalysisSalonEntity(getApplicationContext(), (String) msg.obj);
//				} else {
//					ToastUtil.showShort(getApplicationContext(), "你还没有登录");
//				}
//				Intent intent = new Intent(getApplicationContext(),SalonCollectionMainFragment.class);
//				intent.putExtra("SalonNewActivity", "SalonNewActivity");
//				setResult(0, intent);
//				finish();
				break;
			}
			super.handleMessage(msg);
		}
	};
	private File headerFile;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.salon_new_ui);
		initWidget();
		initData();
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		Intent intent = getIntent();
		if (intent.hasExtra("isDoctorSalon")) {
			isDoctorSalon = intent.getBooleanExtra("isDoctorSalon", false);
		}
		tagId = new StringBuilder();
		tagName = new StringBuilder();
		upperId = new StringBuilder();
		deleteRepeatSet = new HashSet<String>();
		bufferTags = new ArrayList<TagEntity>();
		strs = new ArrayList<String>();
		adapter = new salonInfoTypeAdapter(this, strs);
		adapter.setAddBtnVisable(true);
		mGridView.setAdapter(adapter);

		// 根据医师身份显示布局
		// CustomerInfoEntity entity =
		// SmartFoxClient.getSmartFoxClient().getCustomerInfoEntity();
		if (isDoctorSalon) {
			// 是医师
			isDoctorToggleBtn.setChecked(true);
			isDoctorSalonLinearLayout.setVisibility(View.GONE);
			isAcceptMessageLinearLayout.setBackgroundResource(R.drawable.textview_background_middle);
			isDoctorSalonLinearLayout.setBackgroundResource(R.drawable.textview_background_up);
		} else {
			isDoctorSalonLinearLayout.setVisibility(View.GONE);
			isAcceptMessageLinearLayout.setBackgroundResource(R.drawable.textview_background_up);
		}
	}

	/**
	 * 初始化控件
	 */
	@SuppressLint("ResourceAsColor")
	private void initWidget() {
		mTitle = (TextView) findViewById(R.id.title_lable);
		mTitleBackBtn = (Button) findViewById(R.id.title_back);
		mCreatSalonBtn = (Button) findViewById(R.id.title_right2);
		mSalonName = (EditText) findViewById(R.id.info_name);
		mSalonDescribe = (Button) findViewById(R.id.info_desc);
		isDoctorToggleBtn = (ToggleButton) findViewById(R.id.info_salon_toggleBtn);
		isAcceptMessageToggleBtn = (ToggleButton) findViewById(R.id.message_setting_toggleBtn);
		isOpenToggleButton = (ToggleButton) findViewById(R.id.info_toggleBtn);
		isDoctorSalonLinearLayout = (RelativeLayout) findViewById(R.id.isdoctor_salon);
		isAcceptMessageLinearLayout = (RelativeLayout) findViewById(R.id.message_setting_lin);
		mInfoHeadIv = (ImageView) findViewById(R.id.info_head);
		mGridView = (GridView) findViewById(R.id.label_gv);
		// 设置监听
		mTitle.setOnClickListener(this);
		mCreatSalonBtn.setOnClickListener(this);
		mTitleBackBtn.setOnClickListener(this);
		mInfoHeadIv.setOnClickListener(this);
		mGridView.setOnItemClickListener(this);
		mSalonDescribe.setOnClickListener(this);

		// 初始化数据
		mCreatSalonBtn.setVisibility(View.VISIBLE);
		mCreatSalonBtn.setText("确定");
		mTitle.setText(getString(R.string.create_salon));
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.title_right2:
			createGroup();
			break;
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.info_head:
//			SystemUtils.hideSoftBord(getApplicationContext(), mSalonName);
			showuploadPopWindow();
			break;
		case R.id.galleryadd://从相册获取
//			Intent intent = getPhotoPickIntent();
//			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			}
			try{
				if(!SystemUtils.getScdExit()){
					ToastUtil.showSDCardBusy();
					return;
				}
				Intent intent = CropUtils.createPickForFileIntent();
				startActivityForResult(intent,PHOTO_PICKED_WITH_DATA);
			}catch(Exception e){
				e.printStackTrace();
			}

			break;
		case R.id.cameraadd://相机拍照
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			}
			if(!SystemUtils.getScdExit()){
				ToastUtil.showSDCardBusy();
				return;
			}
			
			try {
				storageFile = StorageUtils.createImageFile();
				Uri outUri = Uri.fromFile(storageFile);
				Intent intent = CropUtils.createPickForCameraIntent(outUri);
				startActivityForResult(intent,CAMERA_REQUESTCODE);
			} catch (Exception e) {
				e.printStackTrace();
				ToastUtil.showCreateFail();
			}
			
//			Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//			storageFile = StorageUtils.createCameraFile();
//			if (storageFile == null) {
//				ToastUtil.showShort(this, "内存卡不可用");
//				return;
//			}
//			Uri uri = Uri.fromFile(storageFile);
//			intent2.putExtra(MediaStore.EXTRA_OUTPUT, uri);
//			startActivityForResult(intent2, CAMERA_REQUESTCODE);

			break;
		case R.id.cancel:
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			}
			break;
		case R.id.info_desc:
			Intent intent1 = new Intent();
			intent1.setClass(getApplicationContext(), CommonExplainActivity.class);
			intent1.putExtra("title", "话题描述");
			intent1.putExtra("mContentCount", 1000); // 字数限制 默认是200
			 intent1.putExtra("content", mSalonDescribe.getText().toString()); // 内容
			startActivityForResult(intent1, 0);
			break;
		}
	}


	/**
	 * 创建话题
	 */
	private void createGroup() {
		final String name = mSalonName.getText().toString();
		final String describe = mSalonDescribe.getText().toString();
		if (name.trim().equals("")) {
			ToastUtil.showLong(this, R.string.inputThemeName);
			return;
		}

		if (name.trim().length() > 40) {
			ToastUtil.showLong(this, R.string.inputThemeLength);
			return;
		}

		if (describe.trim().length() > 1000) {
			ToastUtil.showLong(this, R.string.inputDescLength);
			return;
		}

		if (describe.trim().equals("")) {
			ToastUtil.showLong(this, R.string.inputAddDesc);
			return;
		}

		if (tagId.toString().trim().equals("")) {
			ToastUtil.showShort(getApplicationContext(), "请选择话题类型~");
			return;
		}

		try {
//			String userFileName = "0";
			JSONObject json = new JSONObject();
			json.put("groupId", "");
			json.put("userFileName", "0");
			try {
				json.put("recordName", name);
				json.put("record_desc", describe);
				json.put("infoLayid", tagId.toString().trim());
				json.put("limitNumber", "");
				json.put("inceptMessage", isAcceptMessageToggleBtn
						.isChecked() ? "Y" : "N");
				// 是否将消息发布到消息厅(1-发布，0-不发布)
				json.put("releaseSystemMessage",
						isOpenToggleButton.isChecked() ? "1" : "0");
				if (SmartFoxClient.getLoginUserId()!= null) {
					json.put("custId", SmartFoxClient.getLoginUserId());
				} else {
					Message message = handler.obtainMessage();
					message.what = WHAT_FAILE;
					handler.sendMessage(message);
				}
				// 是否公开创建者信息(Y/N,默认为Y)
				json.put("publicCustInfo", "Y");
				json.put("infoLayName", tagName.toString().trim());
			} catch (Exception e) {
				e.printStackTrace();
			}
			json.put("groupClass", isDoctorToggleBtn.isChecked() ? 1
					: 2);
				HttpRestClient.doHttpNewSalon(getApplicationContext(),
						json.toString(), headerFile,
						new AsyncHttpResponseHandler(SalonNewActivity.this) {
							public void onSuccess(int statusCode,
									String content) {
								super.onSuccess(statusCode, content);
								try {
									if(content!=null && content.contains("error_message")){
										JSONObject jsonObject = new JSONObject(content);
										ToastUtil.showToastPanl(jsonObject.optString("error_message"));
									}else{
										// 此话题名称含有敏感词，此次操作无效！
										isRequestSuccess(content);
									}
								} catch (Exception e) {
								}
							}
						});
		} catch (JSONException e) {
			e.printStackTrace();
		}
	
	}

	private void isRequestSuccess(String content) {
		if (dialog != null) {
			dialog.dismissAllowingStateLoss();
			dialog = null;
		}
		if (content == null || "".equals(content) || !content.contains("{")) {
			Message message = handler.obtainMessage();
			message.what = WHAT_FAILE;
			message.obj = content;
			handler.sendMessage(message);
			return;
		} else {
			if (path != null) {
				ImageUtils.deleBitmap(path);
			}
			Message message = handler.obtainMessage();
			message.obj = content;
			message.what = WHAT_SUCC;
			handler.sendMessage(message);
		}
	};

	/**
	 * 分享弹出框
	 */
	public void showuploadPopWindow() {
		LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(R.layout.interest_image_add_action, null);
		View mainView = inflater.inflate(R.layout.interest_content, null);
		if (mPopupWindow == null) {
			mPopupWindow = new PopupWindow(view, LayoutParams.FILL_PARENT,
					LayoutParams.WRAP_CONTENT);
			mPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		}
		WheelUtils.setPopeWindow(this, mainView, mPopupWindow);
		Button cameraAdd = (Button) view.findViewById(R.id.cameraadd);
		Button galleryAdd = (Button) view.findViewById(R.id.galleryadd);
		Button cancel = (Button) view.findViewById(R.id.cancel);

		cameraAdd.setOnClickListener(this);
		galleryAdd.setOnClickListener(this);
		cancel.setOnClickListener(this);
	}

	/**
	 * 图片裁剪
	 * @param path
	 */
	private void onHandlerCropImage(String path){
		if(!SystemUtils.getScdExit()){
			ToastUtil.showSDCardBusy();
			return;
		}
		try{
			headerFile = StorageUtils.createHeaderFile();
			Uri outUri = Uri.fromFile(new File(path));
			Uri saveUri = Uri.fromFile(headerFile);
			Intent intent = CropUtils.createHeaderCropIntent(this,outUri,saveUri,true);
			startActivityForResult(intent,3002);
		}catch(Exception e){
			ToastUtil.showCreateFail();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case CAMERA_REQUESTCODE://相机拍照
			if(resultCode == Activity.RESULT_OK){
				String strFilePath = storageFile.getAbsolutePath();
				onHandlerCropImage(strFilePath);
			}
			break;
		case PHOTO_PICKED_WITH_DATA://从相册获取
			if(resultCode == Activity.RESULT_OK){
				if (data != null) {
					Uri uri = data.getData();
					String scheme = uri.getScheme();
					String strFilePath = null;//图片地址
					// url类型content or file
					if ("content".equals(scheme)) {
						strFilePath = getImageUrlByAlbum(uri);
					} else {
						strFilePath = uri.getPath();
					}
					onHandlerCropImage(strFilePath);
				}
			}
			
			break;
		case 3002://裁剪后获取结果
			if(resultCode == Activity.RESULT_OK){
				if(resultCode == RESULT_OK){
					Bitmap bitmap = BitmapUtils.decodeBitmap(headerFile.getAbsolutePath(),
							CropUtils.HEADER_WIDTH,
							CropUtils.HEADER_HEIGTH);
					mInfoHeadIv.setImageBitmap(bitmap);
				}else{
					if(headerFile != null)headerFile.deleteOnExit();
					headerFile = null;
				}
			}
			
			break;
		case TAG_CHOOSE_REQUESTCODE://标签返回
			if(resultCode == Activity.RESULT_OK){
				tags = data.getParcelableArrayListExtra("tags");
				bufferTags.clear();
				strs.clear();
				bufferTags.addAll(tags);
				for (TagEntity t : tags) {
					tagName.append(t.getName()).append(",");
					Boolean b = deleteRepeatSet.add(t.getUpperId());
					// 小类全部0不添加
					if (!t.getId().equals("0") && !t.getId().equals("")) {
						tagId.append(t.getId()).append(",");
					}
					// 大类不能重复
					if (b != false) {
						upperId.append(t.getUpperId()).append(",");
					}
					strs.add(t.getName());
				}

				if (tagId.length() != 0) {
					tagId.deleteCharAt(tagId.length() - 1);
				}
				tagName.deleteCharAt(tagName.length() - 1);
				upperId.deleteCharAt(upperId.length() - 1);
				deleteRepeatSet.clear();
				adapter.notifyDataSetChanged();
			
			}
			
			break;
		case 0:
			if(resultCode == Activity.RESULT_OK){
				if (data.hasExtra("content")) {
					mSalonDescribe.setText(data.getExtras().getString("content"));
				}
			}
			break;
		}
		
	}

	/**
	 * 根据uri查询相册所对应的图片地址
	 * @param uri
	 * @return
	 */
	private String getImageUrlByAlbum(Uri uri) {
		String[] imageItems = { MediaStore.Images.Media.DATA };
		Cursor cursor = managedQuery(uri, imageItems, null, null, null);
		int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		String path = cursor.getString(index);
		return path;
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		if (position == strs.size()) {
			Intent intent = new Intent(getApplicationContext(),TagChooseActivity.class);
			if (bufferTags != null && bufferTags.size() > 0) {
				intent.putParcelableArrayListExtra("tags", bufferTags);
			}
			intent.putExtra("resid", R.xml.salon_label);
			startActivityForResult(intent, TAG_CHOOSE_REQUESTCODE);
		}
	}
	@Override
	public void onTicketHandler(String state, GroupInfoEntity entity) {
		if ("0".equals(state)) {
		} else if ("-1".equals(state)) {
			ToastUtil.showShort(this, "服务器出错");
		} else {
			Intent intent1 = new Intent();
			intent1.putExtra(ChatActivity.KEY_PARAME, entity);
			intent1.setClass(this, ChatActivity.class);
			startActivity(intent1);
		}
	}
}
